import { defineStore } from 'pinia'
import type { Task, TaskLog } from '../types/task'
import {
  createTask as createTaskApi,
  getTasks as getTasksApi,
  getMyDayTasks as getMyDayTasksApi,
  getTaskDetail as getTaskDetailApi,
  updateTask as updateTaskApi,
  deleteTask as deleteTaskApi,
  updateTaskGroup as updateTaskGroupApi,
  addTaskLog as addTaskLogApi,
  getTaskLogs as getTaskLogsApi
} from '../services/taskService'

interface TaskState {
  tasks: Task[]
  myDayTasks: Task[]
  currentTask: Task | null
  taskLogs: TaskLog[]
  pagination: {
    page: number
    pageSize: number
    total: number
  }
  filter: {
    groupId: number | null
    status: number | null
    isImportant: boolean | null
    isMyDay: boolean | null
  }
}

export const useTaskStore = defineStore('task', {
  state: (): TaskState => ({
    tasks: [],
    myDayTasks: [],
    currentTask: null,
    taskLogs: [],
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    filter: {
      groupId: null,
      status: null,
      isImportant: null,
      isMyDay: null
    }
  }),

  getters: {
    // 获取所有任务
    getAllTasks: (state) => state.tasks,
    
    // 获取当前任务
    getCurrentTask: (state) => state.currentTask,
    
    // 获取任务日志
    getTaskLogs: (state) => state.taskLogs,
    
    // 根据ID获取任务
    getTaskById: (state) => (taskId: number) => {
      return state.tasks.find(task => task.task_id === taskId)
    },
    
    // 获取重要任务
    getImportantTasks: (state) => {
      return state.tasks.filter(task => task.is_important)
    },
    
    // 获取"我的一天"任务
    getMyDayTasks: (state) => {
      return state.myDayTasks
    }
  },

  actions: {
    // 设置当前任务
    setCurrentTask(task: Task | null) {
      this.currentTask = task
    },
    
    // 设置过滤条件
    setFilter(filter: Partial<TaskState['filter']>) {
      this.filter = { ...this.filter, ...filter }
    },

    // 设置分页
    setPagination(page: number, pageSize: number) {
      this.pagination.page = page
      this.pagination.pageSize = pageSize
    },

    // 获取任务列表
    async fetchTasks() {
      try {
        const params: any = {}
        
        if (this.filter.groupId !== null) {
          params.group_id = this.filter.groupId
        }
        
        if (this.filter.status !== null) {
          params.status = this.filter.status
        }
        
        if (this.filter.isImportant !== null) {
          params.is_important = this.filter.isImportant
        }
        
        if (this.filter.isMyDay !== null) {
          params.is_my_day = this.filter.isMyDay
        }
        
        params.page = this.pagination.page
        params.page_size = this.pagination.pageSize
        
        console.log('Fetching tasks with params:', params)
        const response: any = await getTasksApi(params)
        console.log('=== ACTUAL TASK API RESPONSE ===', JSON.stringify(response, null, 2))
        
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { list: [...], pagination: {...} } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        let tasksData = []
        let total = 0
        
        // 如果response是对象且包含list数组
        if (response && response.success && response.data && response.data.list && Array.isArray(response.data.list)) {
          tasksData = response.data.list
          total = response.data.pagination?.total || 0
          console.log('Tasks data (standard format):', tasksData)
        }
        // 如果response本身就是数组
        else if (response && response.success && Array.isArray(response.data)) {
          tasksData = response.data
          console.log('Tasks data (direct array format):', tasksData)
        }
        // 如果是其他格式
        else {
          console.log('Unknown task data format, setting empty array')
          tasksData = []
        }
        
        this.tasks = tasksData
        this.pagination.total = total
        console.log('Final tasks data:', this.tasks)
        return { success: true, message: response.message || '获取任务列表成功' }
      } catch (error: any) {
        console.error('Error fetching tasks:', error)
        this.tasks = []
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else {
          return { success: false, message: error.message || '获取任务列表失败' }
        }
      }
    },

    // 获取"我的一天"任务列表
    async fetchMyDayTasks() {
      try {
        const response: any = await getMyDayTasksApi()
        console.log('Get my day tasks API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { list: [...], total: ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.list && Array.isArray(response.data.list)) {
          this.myDayTasks = response.data.list
          this.pagination.total = response.data.pagination?.total || 0
          return { success: true, message: response.message || '获取"我的一天"任务列表成功' }
        } else {
          return { success: false, message: response?.message || '获取"我的一天"任务列表失败' }
        }
      } catch (error: any) {
        console.error('Error fetching my day tasks:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else {
          return { success: false, message: error.message || '获取"我的一天"任务列表失败' }
        }
      }
    },

    // 获取任务详情
    async fetchTaskDetail(taskId: number) {
      try {
        // 强制获取最新数据，禁用缓存
        const response: any = await getTaskDetailApi(taskId).send(true)
        console.log('Get task detail API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { task_id: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.task_id) {
          this.currentTask = response.data
          return { success: true, message: response.message || '获取任务详情成功', data: response.data }
        } else {
          return { success: false, message: response?.message || '获取任务详情失败' }
        }
      } catch (error: any) {
        console.error('Error fetching task detail:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '获取任务详情失败' }
        }
      }
    },

    // 创建任务
    async createTask(data: any) {
      try {
        const response: any = await createTaskApi(data)
        console.log('=== CREATE TASK API RESPONSE ===', JSON.stringify(response, null, 2))
        
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { task_id: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        let taskData = null
        
        // 如果response是任务对象
        if (response && response.success && response.data && response.data.task_id) {
          taskData = response.data
          console.log('Task data (standard format):', taskData)
        }
        // 如果是其他格式
        else {
          console.log('Unknown task data format')
          taskData = null
        }
        
        if (taskData && taskData.task_id) {
          // 将新任务添加到任务列表开头
          this.tasks.unshift(taskData)
          this.pagination.total += 1
          
          console.log('New task added to store:', taskData)
          return { success: true, message: response.message || '创建任务成功', data: taskData }
        } else {
          console.log('Task creation failed, invalid response format')
          return { success: false, message: response?.message || '创建任务失败' }
        }
      } catch (error: any) {
        console.error('Error creating task:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else {
          return { success: false, message: error.message || '创建任务失败' }
        }
      }
    },

    // 更新任务
    async updateTask(taskId: number, data: any) {
      try {
        const response: any = await updateTaskApi(taskId, data)
        console.log('Update task API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { task_id: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.task_id) {
          const taskData = response.data
          const index = this.tasks.findIndex(task => task.task_id === taskId)
          if (index !== -1) {
            this.tasks[index] = taskData
          }
          
          // 同时更新myDayTasks中的任务
          const myDayIndex = this.myDayTasks.findIndex(task => task.task_id === taskId)
          if (myDayIndex !== -1) {
            this.myDayTasks[myDayIndex] = taskData
          }
          
          if (this.currentTask && this.currentTask.task_id === taskId) {
            this.currentTask = taskData
          }
          
          return { success: true, message: response.message || '更新任务成功', data: taskData }
        } else {
          return { success: false, message: '更新任务失败' }
        }
      } catch (error: any) {
        console.error('Error updating task:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '更新任务失败' }
        }
      }
    },

    // 删除任务
    async deleteTask(taskId: number) {
      try {
        const response: any = await deleteTaskApi(taskId)
        console.log('Delete task API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: {} }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success) {
          this.tasks = this.tasks.filter(task => task.task_id !== taskId)
          this.pagination.total -= 1
          
          if (this.currentTask && this.currentTask.task_id === taskId) {
            this.currentTask = null
          }
          
          return { success: true, message: response.message || '删除任务成功' }
        } else {
          return { success: false, message: response?.message || '删除任务失败' }
        }
      } catch (error: any) {
        console.error('Error deleting task:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '删除任务失败' }
        }
      }
    },

    // 更新任务分组
    async changeTaskGroup(taskId: number, groupId: number) {
      try {
        const response: any = await updateTaskGroupApi(taskId, { group_id: groupId })
        console.log('Update task group API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { task_id: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.task_id) {
          const taskData = response.data
          const index = this.tasks.findIndex(task => task.task_id === taskId)
          if (index !== -1) {
            this.tasks[index] = taskData
          }
          
          if (this.currentTask && this.currentTask.task_id === taskId) {
            this.currentTask = taskData
          }
          
          return { success: true, message: response.message || '更新任务分组成功', data: taskData }
        } else {
          return { success: false, message: response?.message || '更新任务分组失败' }
        }
      } catch (error: any) {
        console.error('Error changing task group:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '更新任务分组失败' }
        }
      }
    },

    // 添加任务日志
    async addTaskLog(taskId: number, content: string) {
      try {
        const response: any = await addTaskLogApi(taskId, { content })
        console.log('Add task log API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: { log_id: ..., ... } }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && response.data && response.data.log_id) {
          const logData = response.data
          this.taskLogs.push(logData)
          return { success: true, message: response.message || '添加任务日志成功', data: logData }
        } else {
          return { success: false, message: response?.message || '添加任务日志失败' }
        }
      } catch (error: any) {
        console.error('Error adding task log:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 400) {
          return { success: false, message: '输入数据有误，请检查后重试' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '添加任务日志失败' }
        }
      }
    },

    // 获取任务日志列表
    async fetchTaskLogs(taskId: number) {
      try {
        const response: any = await getTaskLogsApi(taskId)
        console.log('Get task logs API response:', response)
        // 根据接口设计文档，API返回格式为 { code: 1, success: true, message: "", data: [...] }
        // Alova已经提取了response.data，所以response就是data字段的内容
        if (response && response.success && Array.isArray(response.data)) {
          this.taskLogs = response.data
          return { success: true, message: response.message || '获取任务日志列表成功' }
        } else {
          return { success: false, message: response?.message || '获取任务日志列表失败' }
        }
      } catch (error: any) {
        console.error('Error fetching task logs:', error)
        // 根据错误类型返回不同的错误消息
        if (error.code === 'NETWORK_ERROR') {
          return { success: false, message: '网络连接失败，请检查网络设置' }
        } else if (error.response?.status === 401) {
          return { success: false, message: '登录已过期，请重新登录' }
        } else if (error.response?.status === 404) {
          return { success: false, message: '任务不存在' }
        } else {
          return { success: false, message: error.message || '获取任务日志列表失败' }
        }
      }
    }
  }
})